package com.yj.suncity.activity.shouye;

import java.util.List;

import org.json.JSONObject;

import com.yj.suncity.R;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.ThreadUtils;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.async.ThreadUtils.OnResultListener;
import com.yj.suncity.bean.OfferDetailGoodsBean;
import com.yj.suncity.bean.OfferDetailListBean;
import com.yj.suncity.bean.OfferDetailOfferBean;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.user.LoginActivity;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.PagerScrollView;
import com.yj.suncity.utis.SharedPreferencesUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.Utils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout.LayoutParams;

public class OfferDetailListActivity extends Activity implements
		OnClickListener {
	private Context context;
	private String offerUserId;
	private String offerId;

	private ImageView mImg_logo;
	private TextView mTxt_shop_name, mTxt_shop_jianjie, mTxt_al_see_adv,
			mTxt_al_duihuan, mTxt_al_digou, mTxt_al_offer;// 详情顶部

	private TextView mTxt_contact_name, mTxt_contact_phone,
			mTxt_contact_address;// 联系

	private HorizontalScrollView horizontalScrollView;
	private LinearLayout mLay_linear_goods;
	private int mWidth;
	private DisplayImageOptions options;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private ListView mListView;
	private OfferDetailListBean listBean;
	private PagerScrollView scrollView;
	private SharedPreferencesUtil preferencesUtil = SharedPreferencesUtil
			.getInstance();
	private boolean isLogin;
	private ImageView mImag_collect_normal, mImag_collect_press;
	private boolean isCollect;
	private String userId;
	private String shopId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_offer_detail_list);
		context = this;
		offerId = getIntent().getStringExtra("offerid");
		offerUserId = getIntent().getStringExtra("offeruserid");
		mWidth = getResources().getDisplayMetrics().widthPixels;
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				// .displayer(new RoundedBitmapDisplayer(10))// 设置成圆角图片
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		findView();
		initData();
	}

	private void findView() {
		scrollView = (PagerScrollView) findViewById(R.id.scroll_view);
		findViewById(R.id.btnHeadBack).setOnClickListener(this);
		findViewById(R.id.lay_rela_collect).setOnClickListener(this);
		findViewById(R.id.lay_linear_zhaiyao).setOnClickListener(this);
		mImag_collect_normal = (ImageView) findViewById(R.id.img_collet_normal);
		mImag_collect_press = (ImageView) findViewById(R.id.img_collet_press);

		mListView = (ListView) findViewById(R.id.list_view_offer_detail);

		mLay_linear_goods = (LinearLayout) findViewById(R.id.lay_linear_goods);
		horizontalScrollView = (HorizontalScrollView) findViewById(R.id.lay_horizontal_ScrollView);

		horizontalScrollView.setLayoutParams(new LinearLayout.LayoutParams(
				mWidth, (mWidth - (Utils.dipTopx(context, 10))) / 4));

		mImg_logo = (ImageView) findViewById(R.id.img_logo);
		mTxt_shop_name = (TextView) findViewById(R.id.txt_shop_name);
		mTxt_shop_jianjie = (TextView) findViewById(R.id.txt_shop_jianjie);
		mTxt_al_see_adv = (TextView) findViewById(R.id.txt_al_see_adv);
		mTxt_al_duihuan = (TextView) findViewById(R.id.txt_al_duihuan);
		mTxt_al_digou = (TextView) findViewById(R.id.txt_al_digou);
		mTxt_al_offer = (TextView) findViewById(R.id.txt_al_offer);

		mTxt_contact_name = (TextView) findViewById(R.id.txt_contact_name);
		mTxt_contact_phone = (TextView) findViewById(R.id.txt_contact_phone);
		mTxt_contact_address = (TextView) findViewById(R.id.txt_contact_address);
	}

	private void initData() {
		String path = URLCon.悬赏 + "?action=acceptofferdetail&txtuserid="
				+ offerUserId;
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "正在加载......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						listBean = new OfferDetailListBean(jsonObject);
						int dip_5 = Utils.dipTopx(context, 5);
						for (final OfferDetailGoodsBean goodsBean : listBean
								.getGoods_img()) {
							ImageView imageView = new ImageView(context);
							imageView.setLayoutParams(new LayoutParams(
									(mWidth - 2 * dip_5) / 4,
									(mWidth - 2 * dip_5) / 4));
							imageView.setScaleType(ScaleType.CENTER_CROP);
							imageView.setPadding(dip_5, dip_5, dip_5, dip_5);
							if (goodsBean.getImg_url().contains(",")) {
								imageLoader.displayImage(
										URLCon.HOST
												+ (goodsBean.getImg_url()
														.split(","))[0],
										imageView, options);
							} else {
								imageLoader.displayImage(URLCon.HOST
										+ goodsBean.getImg_url(), imageView,
										options);
							}
							mLay_linear_goods.addView(imageView);
							imageView.setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View v) {
									Intent intent = new Intent(context,
											ProductDateilsActivity.class);
									intent.putExtra("goodid", goodsBean.getId());
//									intent.putExtra("flag", flag);
									startActivity(intent);
								}
							});
							
						}
						setViewValue();
					}
				});
		asyncTaskUtil.execute(path);
	}

	private void setViewValue() {
		imageLoader.displayImage(URLCon.HOST + listBean.getEnt_logo(),
				mImg_logo, options);
		shopId = listBean.getUserid();
		mTxt_shop_name.setText(listBean.getEntname());
		mTxt_shop_jianjie.setText(listBean.getEnt_jianjie());
		mTxt_al_see_adv.setText(listBean.getSee_num());
		mTxt_al_duihuan.setText(listBean.getDh_num());
		mTxt_al_digou.setText(listBean.getDg_num());
		mTxt_al_offer.setText(listBean.getHold_num());

		mTxt_contact_name.setText(listBean.getEnt_contact());
		mTxt_contact_phone.setText(listBean.getEnt_contact_tel());
		mTxt_contact_address.setText(listBean.getEnt_address());
		mTxt_contact_phone.setOnClickListener(new OnClickListener() {// 拨打电话
					@Override
					public void onClick(View v) {
						DialogUtils dialogUtils = DialogUtils.getInstance();
						dialogUtils.CallDialog(context,
								listBean.getEnt_contact_tel());
					}
				});
		mListView.setAdapter(new OfferAdapter(listBean.getOffer()));
		scrollView.post(new Runnable() {
			@Override
			public void run() {
				scrollView.scrollTo(0, 0);

			}
		});
	}

	class OfferAdapter extends BaseAdapter {
		private List<OfferDetailOfferBean> offerBeans;

		public OfferAdapter(List<OfferDetailOfferBean> offerBeans) {
			this.offerBeans = offerBeans;
		}

		@Override
		public int getCount() {
			return offerBeans.size();
		}

		@Override
		public Object getItem(int position) {
			return offerBeans.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(
						R.layout.adapter_offer_detail_item, null);
				holder.mImg_btn_jieoffer = (ImageView) convertView
						.findViewById(R.id.img_btn_jieoffer);
				holder.mTxt_content = (TextView) convertView
						.findViewById(R.id.txt_offer_content);
				holder.mTxt_offer_num = (TextView) convertView
						.findViewById(R.id.txt_give_num);
				holder.mTxt_jie_num = (TextView) convertView
						.findViewById(R.id.txt_num);
				holder.mTxt_offer_end_time = (TextView) convertView
						.findViewById(R.id.txt_end_time);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final OfferDetailOfferBean offerBean = offerBeans.get(position);
			holder.mTxt_content.setText(offerBean.getOffer_content());
			holder.mTxt_offer_end_time.setText(Utils.DateFormatDate(offerBean
					.getEnd_datetime()));
			holder.mTxt_offer_num.setText(offerBean.getOffer_givenum());
			holder.mTxt_jie_num.setText(offerBean.getOffer_num());

			holder.mImg_btn_jieoffer.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(context,
							OfferDetailActivity.class);
					intent.putExtra("offerid", offerBean.getId());
					intent.putExtra("endtime", offerBean.getEnd_datetime());
					intent.putExtra("offercontent",
							offerBean.getOffer_content());
					intent.putExtra("offergivenum",
							offerBean.getOffer_givenum());
					intent.putExtra("offernum", offerBean.getOffer_num());
					intent.putExtra("entname", listBean.getEntname());
					intent.putExtra("entlogo", listBean.getEnt_logo());
					intent.putExtra("enttel", listBean.getEnt_contact_tel());
					startActivity(intent);
				}
			});

			return convertView;
		}
	}

	class ViewHolder {
		ImageView mImg_btn_jieoffer;
		TextView mTxt_content;
		TextView mTxt_offer_end_time;
		TextView mTxt_offer_num;
		TextView mTxt_jie_num;
	}

	@Override
	protected void onResume() {
		isLogin = preferencesUtil.getBoolean(context, ShareCon.USERFILE,
				ShareCon.ISLOGIN, false);
		// isShop = preferencesUtil.getBoolean(context, ShareCon.USERFILE,
		// ShareCon.USERTYPE, false);
		if (isLogin) {
			userId = preferencesUtil.getString(context, ShareCon.USERFILE,
					ShareCon.USERID, "");
			getCollectStatus();
		}
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		case R.id.lay_linear_zhaiyao:
			Intent intshop = new Intent(this, ShopGoodsListActivity.class);
			intshop.putExtra("titlename", "全部商品");
			intshop.putExtra("userid", shopId);
			startActivity(intshop);
			break;
		case R.id.lay_rela_collect:// 添加/移除收藏
			if (!isLogin) {
				startActivity(new Intent(this, LoginActivity.class));
				return;
			}
			if (isCollect) {
				removeCollect();
			} else {
				addCollect();
			}

		default:
			break;
		}
	}

	private void addCollect() {
		String path = URLCon.收藏 + "?action=addcollection&userid=" + userId
				+ "&id=" + offerId + "&type=3";
		Log.d("", "添加收藏：" + path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "添加收藏......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							isCollect = true;
							mImag_collect_normal.setVisibility(View.GONE);
							mImag_collect_press.setVisibility(View.VISIBLE);
							ToastUtil.ShowToast(context, "收藏成功！");
						} else {
							ToastUtil.ShowToast(context,
									"" + jsonObject.optString("msg"));
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	private void getCollectStatus() {
		String path = URLCon.收藏 + "?action=getcollectionstate&userid=" + userId
				+ "&id=" + offerId + "&type=3";
		Log.d("", "获取收藏：" + path);
		ThreadUtils threadUtils = new ThreadUtils();
		threadUtils.startThread(path, new OnResultListener() {
			@Override
			public void jsonResult(JSONObject json) {
				if (json.optString("success").equals("1")) {
					if (json.optString("state").equals("1")) {
						isCollect = true;
						mImag_collect_normal.setVisibility(View.GONE);
						mImag_collect_press.setVisibility(View.VISIBLE);
					} else {
						isCollect = false;
						mImag_collect_normal.setVisibility(View.VISIBLE);
						mImag_collect_press.setVisibility(View.GONE);
					}
				}
			}
		});
	}

	private void removeCollect() {
		String path = URLCon.收藏 + "?action=delcollection&userid=" + userId
				+ "&id=" + offerId;

		Log.d("", "添加收藏：" + path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "删除收藏......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							isCollect = false;
							setResult(1);
							mImag_collect_normal.setVisibility(View.VISIBLE);
							mImag_collect_press.setVisibility(View.GONE);
							ToastUtil.ShowToast(context, "删除收藏成功！");
						} else {
							ToastUtil.ShowToast(context,
									"" + jsonObject.optString("msg"));
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

}
